<?php

namespace Service;

use Doctrine\ORM\EntityManager;

class UserManager extends Manager
{

    protected function _getEntityClass()
    {
        return 'User';
    }

    public function sendEmail(User $user)
    {
        $message = "test";
        mail('test@example.com', 'My Subject', $message);
    }

    public function create(array $data)
    {
        if (!isset($data['group'])) {
            $data['group'] = 1;
        }

        if (isset($data['parent'])) {
            $parent = $this->_em->find("\Entity\User", $data['parent']);
            $data['parent'] = $parent;
        }

        $group = $this->_em->find("\Entity\Group", $data['group']);
        $data['group'] = $group;

        return parent::create($data);
    }

    public function update($data, $id)
    {
        if (isset($data['group'])) {
            $data['group'] = $this->_em->find("\Entity\Group", $data['group']);
        } 
        
        if (isset($data['user_parent'])){
            $data['parent'] = $this->_em->find("\Entity\User", $data['user_parent']);
        }
        parent::update($data, $id);
    }

    public function isValidUserName($name)
    {
        //$name = 'admin';
        if (null === $name || strlen($name) == 0) {
            throw new \Exception("Invalid user name!");
        }
        $user = $this->_em->getRepository("\Entity\User")->findOneByName($name);
        if ($user) {
            return false;
        }
        return true;
    }

    public function isValidUserEmail($email)
    {
        //$name = 'admin';
        if (null === $email || strlen($email) == 0) {
            throw new \Exception("Invalid user email!");
        }
        $user = $this->_em->getRepository("\Entity\User")->findOneByEmail($email);
        if ($user) {
            return false;
        }
        return true;
    } 
    
    public function getSumAgentBalance(\Entity\User $user)
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->select("SUM(u.balance)")
                ->from("Entity\User", "u")
                ->where($qb->expr()->gt('u.lft', ':ltf'))
                ->andWhere($qb->expr()->lt('u.rgt', ':rgt'))
                ->setParameter("ltf", $user->getLeft())
                ->setParameter("rgt", $user->getRight());
        return $qb->getQuery()->getSingleScalarResult();
    }

}